package cn.wm.e_02.define_protocol.handler;

import cn.hutool.core.lang.UUID;
import cn.wm.e_02.define_protocol.domain.RpcProtocol;
import cn.wm.e_02.define_protocol.domain.RpcProtocolHeader;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ClientMessageHandler extends SimpleChannelInboundHandler<RpcProtocol> {
    private final String endpoint;

    public ClientMessageHandler(String endpoint) {
        this.endpoint = endpoint;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 100; i++) {
            RpcProtocol rpcProtocol = new RpcProtocol();
            rpcProtocol.setBody(String.format("hello server %d", i).getBytes());
            rpcProtocol.setStart(1);
            RpcProtocolHeader header = new RpcProtocolHeader();
            header.setId(UUID.randomUUID().toString());
            header.setVersion("V1.0");
            rpcProtocol.setHeader(header);
            ctx.channel().writeAndFlush(rpcProtocol);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcProtocol msg) throws Exception {
        System.out.printf("%s收到消息：----------\n", endpoint);
        System.out.printf("头信息：%s\n", msg.getHeader());
        System.out.printf("内容：%s\n", new String(msg.getBody()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}
